import { ref } from 'vue'
import FyDialog from '@/components/common/FyDialog/index.js' // 引入 FyDialog
import MenuForm from '@/pages/System/components/MenuForm.vue' // 引入 MenuForm 组件

const useMenuManagement = (routes) => {
  const menuList = ref([]) // 菜单列表
  const selected = ref([]) // 选中的菜单
  const ticked = ref([]) // 勾选的菜单

  // 初始化菜单数据
  const initializeMenuData = (routes, level = 0) => {
    return routes.map((route) => ({
      title: route.meta.title, // 从meta中获取title
      icon: route.meta.icon, // 从meta中获取icon
      id: route.path, // 菜单路径
      path: route.path, // 添加 path 字段
      component: route.component, // 添加 component 字段
      level, // 添加 level 字段
      children: route.children ? initializeMenuData(route.children, level + 1) : [],
      enabled: route.meta.enabled || true, // 是否启用
    }))
  }

  // 加载菜单数据
  menuList.value = initializeMenuData(routes)

  // 新增菜单
  const addMenu = async () => {
    const result = await FyDialog.form(MenuForm, {
      title: '新增菜单',
      menu: {},
    })

    if (result) {
      menuList.value.push({
        title: result.title,
        path: result.path,
        component: result.component,
        level: 0,
        children: [],
        enabled: true,
      })
    }
  }

  // 编辑菜单
  const editMenu = async (node) => {
    const result = await FyDialog.form(MenuForm, {
      title: '编辑菜单',
      menu: { ...node },
    })

    if (result) {
      node.title = result.title
      node.path = result.path
      node.component = result.component
    }
  }

  // 删除菜单
  const deleteMenu = async (node) => {
    const result = await FyDialog.confirm(`确定要删除菜单 "${node.title}" 吗？`)
    if (result) {
      // 从菜单列表中删除
      menuList.value = menuList.value.filter((menu) => menu.id !== node.id)
    }
  }

  // 处理节点选择
  const onNodeSelect = (node) => {
    console.log('选中节点:', node)
    // 处理菜单编辑或查看逻辑
  }

  return { menuList, selected, ticked, addMenu, editMenu, deleteMenu, onNodeSelect }
}

export default useMenuManagement
